package com.ny.controller;

import com.ny.entity.Classrooms;
import com.ny.entity.Users;
import com.ny.service.ClassroomService;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ClassroomService classroomService;
    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpSession session){
        Users user = userService.findUserByUsernameAndPassword(username,password);
        session.setAttribute("user",user);
        if (user!=null && user.getRole().equals("学生")) {
            List<Classrooms> classroomsList = classroomService.findAllClassrooms();
            model.addAttribute("classroomsList",classroomsList);
            return "classroom";
        }
        else {
            return "login";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "login";
    }
    @GetMapping("/searchClassrooms")
    public String searchClassrooms(
            @RequestParam(required = false) String classroomName,
            @RequestParam(required = false) String capacity,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String building,
            @RequestParam(required = false) String description,
            Model model) {
        List<Classrooms> classroomsList = classroomService.searchClassrooms(classroomName, capacity, status, building, description);
        System.out.println("获取到的数据"+classroomsList);
        model.addAttribute("classroomsList", classroomsList);
        return "classroom";
    }
}
